package com.huluobo.a2111douyindemo.video;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.PagerSnapHelper;
import androidx.recyclerview.widget.RecyclerView;

import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.EditText;

import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.huluobo.a2111douyindemo.R;
import com.huluobo.a2111douyindemo.adapter.CommentAdapter;
import com.huluobo.a2111douyindemo.adapter.MultiVideoAdapter;
import com.huluobo.a2111douyindemo.adapter.VideoAdapter;
import com.huluobo.a2111douyindemo.databinding.FragmentVideoBinding;
import com.huluobo.a2111douyindemo.live.LiveActivity;
import com.huluobo.mvvm_base.mvvm.base.view.BaseMVVMFragment;
import com.huluobo.mvvm_base.mvvm.bean.CommentBeanResult;
import com.huluobo.mvvm_base.mvvm.bean.FollowBeanResult;
import com.huluobo.mvvm_base.mvvm.bean.LikeVideoBeanResult;
import com.huluobo.mvvm_base.mvvm.bean.VideoBeanResult;
import com.shuyu.gsyvideoplayer.video.StandardGSYVideoPlayer;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMWeb;

import java.util.ArrayList;
import java.util.List;

public class VideoFragment extends BaseMVVMFragment<FragmentVideoBinding, VideoViewModel> {

    private int currentPage = 1;

    //当前播放的是哪个视频的下标
    private int currentPosition = 0;
    private StandardGSYVideoPlayer player;

    //适配器
//    private VideoAdapter videoAdapter;
    private MultiVideoAdapter videoAdapter;

    //评论适配器
    private CommentAdapter commentAdapter;
    //评论数据源
    private List<CommentBeanResult.CommentBean> commentBeans = new ArrayList<>();

    //数据源
    private List<VideoBeanResult.VideoBean> videoBeanList = new ArrayList<>();

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_video;
    }

    @Override
    protected void initData() {
        //页面初始化加载视频列表
        viewModel.getVideoList(currentPage, 10);

        //视频列表成功的数据
        viewModel.success.observe(this, videoBeanResult -> {
            videoBeanList.clear();
//            videoBeanList.addAll(videoBeanResult.getData());
            videoAdapter.getData().addAll(videoBeanResult.getData());
            videoAdapter.notifyDataSetChanged();
        });

        //视频列表失败的数据
        viewModel.failed.observe(this, s -> {
            Log.i("TagA", "videosFailed:" + s);
        });

        //点赞成功
        viewModel.likeSuccess.observe(this, likeVideoBeanResult -> {
            if (likeVideoBeanResult.getCode() == 200) {
                ToastUtils.showLong(likeVideoBeanResult.getMessage());
                //更新数据源
                videoAdapter.getData().get(currentPosition).setDianzan(1);
                //单独刷新适配器
                videoAdapter.notifyItemChanged(currentPosition);
            } else {
                ToastUtils.showLong(likeVideoBeanResult.getMessage());
            }
        });

        //点赞失败
        viewModel.likeFailed.observe(this, s -> {
            ToastUtils.showLong(s);
        });

        //取消点赞成功
        viewModel.noLikeSuccess.observe(this, likeVideoBeanResult -> {
            if (likeVideoBeanResult.getCode() == 200) {
                ToastUtils.showLong(likeVideoBeanResult.getMessage());
                //更新数据源
                videoAdapter.getData().get(currentPosition).setDianzan(0);
                //单独刷新适配器
                videoAdapter.notifyItemChanged(currentPosition);
            } else {
                ToastUtils.showLong(likeVideoBeanResult.getMessage());
            }
        });

        //取消点赞失败
        viewModel.noLikeFailed.observe(this, s -> {
            ToastUtils.showLong(s);
        });

        //关注成功
        viewModel.followSuccess.observe(this, followBeanResult -> {
            if (followBeanResult.getCode() == 200) {
                ToastUtils.showLong(followBeanResult.getMessage());
                videoAdapter.getData().get(currentPosition).setGuanzhu(1);
                videoAdapter.notifyItemChanged(currentPosition);
            }
        });

        //关注失败
        viewModel.followFailed.observe(this, s -> {
            ToastUtils.showLong(s);
        });

        //获取评论列表成功
        viewModel.getCommentSuccess.observe(this, commentBeanResult -> {
            if (commentBeanResult.getCode() == 200) {
                commentBeans.clear();
                commentBeans.addAll(commentBeanResult.getData());
                commentAdapter.notifyItemChanged(currentPosition);
            } else {
                ToastUtils.showLong(commentBeanResult.getMessage());
            }
        });

        //获取评论列表失败
        viewModel.getCommentFailed.observe(this, s -> {
            Log.i("TagA", "commentFailed:" + s);
        });

        //发布评论成功
        viewModel.sendCommentSuccess.observe(this, commentBeanResult -> {
            if (commentBeanResult.getCode() == 200) {
                //在评论列表的第0位添加最新评论
                commentAdapter.getData().addAll(0, commentBeanResult.getData());
                commentAdapter.notifyDataSetChanged();

                //拿到评论的rv,滚动到最新的位置
                RecyclerView commentRv = (RecyclerView) videoAdapter.getViewByPosition(currentPosition,
                        R.id.item_video_comment_rv);
                if (commentRv != null) {
                    commentRv.scrollToPosition(0);
                }

                //拿到输入框,清空
                EditText editMsg = (EditText) videoAdapter.getViewByPosition(currentPosition, R.id.item_video_input_et);
                assert editMsg != null;//与if(editMsg!=null)同理
                editMsg.setText("");

            } else {
                ToastUtils.showLong(commentBeanResult.getMessage());
            }
        });

        //发布评论失败
        viewModel.sendCommentFailed.observe(this, s -> {

        });
    }

    @Override
    protected void initView() {
        LinearLayoutManager layoutManager = new LinearLayoutManager(requireContext());
        dataBinding.videoRv.setLayoutManager(layoutManager);
        //仿抖音上下翻页功能
        //使用页面打开控制器来使RecyclerView添加翻页功能
        PagerSnapHelper pagerSnapHelper = new PagerSnapHelper();
        pagerSnapHelper.attachToRecyclerView(dataBinding.videoRv);

        videoAdapter = new MultiVideoAdapter();
        videoAdapter.getData().addAll(videoBeanList);//直接通过adapter的data给数据源赋值
        dataBinding.videoRv.setAdapter(videoAdapter);


        //获取视频列表的RecyclerView,添加滚动监听器,获取滚动,然后自动播放
        dataBinding.videoRv.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                //获取当前展示item(滑动)的位置
                currentPosition = layoutManager.findFirstVisibleItemPosition();
                //获取播放器播放
                player = (StandardGSYVideoPlayer) videoAdapter.getViewByPosition(currentPosition,
                        R.id.item_video_gsy_player);
                if (player != null) {
                    player.startPlayLogic();
                }
            }
        });

        //添加点击事件的id
        videoAdapter.addChildClickViewIds(R.id.item_video_add_iv, R.id.item_video_like_iv, R.id.item_video_comment_iv
                , R.id.item_video_close, R.id.item_video_send_iv, R.id.item_video_share_iv, R.id.item_video_full_iv,
                R.id.item_video_live_iv);

        //设置点击事件
        videoAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
            @Override
            public void onItemChildClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
                //获取当前视频的实例类
                VideoBeanResult.VideoBean videoBean = (VideoBeanResult.VideoBean) adapter.getData().get(position);
                //从adapter中拿到数据源
//                VideoBeanResult.VideoBean videoBean1 = videoBeanList.get(position);//是从当前fragment中的list拿到数据源
                switch (view.getId()) {
                    case R.id.item_video_add_iv:
                        addFollow(videoBean);
                        break;
                    case R.id.item_video_like_iv:
                        likeVideo(videoBean);
                        break;
                    case R.id.item_video_comment_iv:
                        showComment(videoBean);
                        break;
                    case R.id.item_video_close:
                        closeComment();
                        break;
                    case R.id.item_video_send_iv:
                        sendComment(videoBean);
                        break;
                    case R.id.item_video_share_iv:
                        shareVideo(videoBean);
                        break;
                    case R.id.item_video_full_iv:
                        fullScreenPlayer(videoBean);
                        break;
                    case R.id.item_video_live_iv:
                        toLive(videoBean);
                        break;
                }
            }
        });
    }

    private void toLive(VideoBeanResult.VideoBean videoBean) {
        Intent intent = new Intent(requireContext(), LiveActivity.class);
        intent.putExtra("videoBean",videoBean);
        startActivity(intent);
    }

    private void fullScreenPlayer(VideoBeanResult.VideoBean videoBean) {
        if (player != null) {
            player.setRotateViewAuto(true);//自动翻转屏幕
            player.startWindowFullscreen(requireContext(), false, true);//设置全屏
            player.startPlayLogic();
        }
    }

    //分享视频
    private void shareVideo(VideoBeanResult.VideoBean videoBean) {
        //设置分享的缩略图
        UMImage umImage = new UMImage(requireContext(), videoBean.getVideomainimg());//图片地址
        umImage.compressStyle = UMImage.CompressStyle.SCALE;//压缩图片大小

        UMWeb web = new UMWeb(videoBean.getVideopath());//分享视频的地址
        web.setTitle(videoBean.getAuthname());//设置标题
        web.setThumb(umImage);//设置缩略图
        web.setDescription(videoBean.getCaption());//设置描述

        //触发分享
        new ShareAction(requireActivity())
                .withMedia(web)//填入分享内容
                .open();
    }

    //发布评论
    private void sendComment(VideoBeanResult.VideoBean videoBean) {
        //拿到输入框
        EditText sendEdit = (EditText) videoAdapter.getViewByPosition(currentPosition, R.id.item_video_input_et);
        if (sendEdit != null) {
            String sendMsg = sendEdit.getText().toString().trim();
            if (TextUtils.isEmpty(sendMsg)) {
                ToastUtils.showLong("请输入文本,注意文明用语!");
                return;
            }
            viewModel.sendComment(sendMsg, videoBean.getId());
        }
    }

    //关闭评论布局
    private void closeComment() {
        //获取评论布局
        View commentLayout = videoAdapter.getViewByPosition(currentPosition, R.id.item_video_comment_ll);
        commentLayout.setVisibility(View.VISIBLE);
        //加载动画
        Animation animationOut = AnimationUtils.loadAnimation(requireContext(), R.anim.anim_out);
        animationOut.setDuration(500);
        animationOut.setInterpolator(new AccelerateInterpolator());//加速插值器,越来越快
        animationOut.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                commentLayout.setVisibility(View.GONE);
                //恢复RecyclerView的拦截事件
                dataBinding.videoRv.setIntercept(true);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
        commentLayout.startAnimation(animationOut);
    }

    //打开评论布局
    private void showComment(VideoBeanResult.VideoBean videoBean) {
        //展示评论布局的同时,拦截RecyclerView的事件
        dataBinding.videoRv.setIntercept(false);
        //获取评论布局
        View commentLayout = videoAdapter.getViewByPosition(currentPosition, R.id.item_video_comment_ll);
        commentLayout.setVisibility(View.VISIBLE);
        //加载动画
        Animation animationIn = AnimationUtils.loadAnimation(requireContext(), R.anim.anim_in);
        animationIn.setDuration(500);
        animationIn.setInterpolator(new AccelerateInterpolator());//加速插值器,越来越快
        animationIn.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
                //通过视频id获取评论列表
                viewModel.getCommentByVideoId(videoBean.getId());
            }

            @Override
            public void onAnimationEnd(Animation animation) {

            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
        //执行动画
        commentLayout.startAnimation(animationIn);

        //初始化评论列表
        RecyclerView commentRv = (RecyclerView) videoAdapter.getViewByPosition(currentPosition,
                R.id.item_video_comment_rv);
        commentRv.setLayoutManager(new LinearLayoutManager(requireContext()));
        commentAdapter = new CommentAdapter(commentBeans);
        commentRv.setAdapter(commentAdapter);
    }

    //点赞视频的方法
    private void likeVideo(VideoBeanResult.VideoBean videoBean) {
        if (videoBean.getDianzan() == 0) {
            viewModel.likeVideo(videoBean.getId());
        } else {
            viewModel.noLikeVideo(videoBean.getId());
        }
    }

    //关注用户的方法
    private void addFollow(VideoBeanResult.VideoBean videoBean) {
        viewModel.followAuth(videoBean.getAuthname());
    }

    @Override
    protected Class<VideoViewModel> getViewModel() {
        return VideoViewModel.class;
    }
}